window.mofang.moniter.taskGroup = function() {

	var cache = {};
	var params = {data:{page : 1, pageSize : 10 , status : 'ALL'}, url : 'monitor/Task/findTaskByChannel.koala'};
	var channelData = {};
	var isProxyIps = {1 : '使用', 0 : '不使用'};
	var taskStatus = {'ALL' : '全部', 'FINISHED' : '已完成', 'DOING' : '执行中', 'NORUN' : '未执行', 'EXCEPTION' : '失败', 'PAUSE' : '暂停', 'CANCEL' : '取消'};

	var init = function() {
		util.mofangAjax({
			url : 'monitor/Task/findGroup.koala',
			async : false,
			succFun : function(json) {
				cache.channel = $.parseJSON(json.channel);
				cache.groupRoot = $.parseJSON(json.groupRoot);
				cache.groups = $.parseJSON(json.groups);
			}
		});
		channelDataInit();
		groupTreeInit();
		
		// 任务显示init
		_grid.init();
		pageTool.init();
		domEventInit();
		requestData();
	};
	
	
	var domEventInit = function() {
		$('#monitor_taskstaus_serach').find('a').unbind('click').bind('click',function(e){
			params.data.page = 1;
			params.data.status = $(this).attr('active');
			$("#showSelected").empty().append(taskStatus[params.data.status]);
			requestData();
		});
		
	};
	
	var channelDataInit = function() {
		var channelMap = {};//渠道信息
		var groupMap = {};//组信息
		
		$.each(cache.channel.data, function(i, data) {
			var key = $.trim(data.remarks || data.id);
			channelMap[key] = data;
			var channels = channelData[data.group] || [];
			channels.push(data);
			channelData[data.group] = channels;
		});
		
		$.each(cache.groups.data, function(i, data) {
			groupMap[data.id] = data;
		});
		
		cache['channelMap'] = channelMap;
		cache['groupMap'] = groupMap;
	};

	var groupTreeInit = function() {
		var top = {
			name : '根结点',
			icon : 'css/zTreeStyle/img/diy/1_open.png',
			open : true,
			children : []
		};

		$.each(cache.groupRoot.data, function(i, data) {
			var node = {};
			node['id'] = data.id;
			node['name'] = data.name;

//			if (data.children && data.children.length > 0) {
				node['open'] = false;
				node['children'] = [];
				dataFormat(data.children, node);
//			} else {
//				node['children'] = [];
				channelNodeAppend(node.children, channelData[data.id]);
//			}

			top.children.push(node);
		});

		// ztree控件
		var setting = {
			view : {
				dblClickExpand : function(treeId, treeNode) {
					return treeNode.level > 0;
				}
			},
			callback : {
				onClick : function(event, treeId, node) {
					// 只有子点点才加载数据
					if (node.channel) {
						params.data.channelId = node.id;
						requestData();
					}
				}
			}
		};

		ztree = $.fn.zTree.init($('#taskmonitor_tree'), setting, [ top ]);

	};

	var dataFormat = function(childrens, parent) {
		$.each(childrens, function(i, children) {
			var node = {};
			node['id'] = children.id;
			node['name'] = children.name;

//			if (children.children && children.children.length > 0) {
				node['open'] = false;
				node['children'] = [];
				dataFormat(children.children, node);
//			} else {
//				// 获取组下面的渠道
//				node['children'] = [];
				channelNodeAppend(node.children, channelData[children.id]);
//			}

			parent.children.push(node);
		});
	};
	
	var channelNodeAppend = function(children, datas) {
		if (!datas) {
			return ;
		}
		
		$.each(datas, function(i, data) {
			var node = {};
			node['id'] = data.remarks || data.id;
			node['name'] = data.name;
			node['icon'] = 'css/zTreeStyle/img/diy/3.png';
			node['channel'] = true;
			children.push(node);
		});
	};
	
	var pageTool = page({
		renderTo : "monitor_task_Page",
		pageSize : params.data.pageSize,
		subHandler : function(data) {
			params.data.page = data.currNo;
			params.data.pageSize = data.pageSize;
			requestData();
		}
	});
	
	var _grid = grid({
		renderTo 	: 'monitor_task_grid', 
	    checkboxs   : {	
	    					checkbox  : true,
	    					checkAll  : true,
	    					dataIndex : 'id'
	    				},
		columns  : [ 	{name : '任务编号', dataIndex : 'id', overflow : true},
		             	{name : '任务开始时间', dataIndex : 'taskStartDate'},
		             	{name : '任务结束时间', dataIndex : 'taskEndDate'},
		             	{name : '花费时间', funHandler : function(data){
		             		if(data.taskEndDate == ''){
		             			return '-';
		             		} else {
		             			return data.taskExcuteTotal + ' 毫秒';
		             		}
		             	}},
		             	{name : '所属渠道', dataIndex : 'channelName'}, 
		             	{name : '是否使用代理', funHandler : function(data){
		             		 return isProxyIps[data.isProxyIp];
		             			}
		             		}, 
		             	{name : '任务状态', renderer : function(data){
//		             		if('EXCEPTION' === data.taskState){
//		             			return '<a id="g_exception">' + taskStatus[data.taskState] + '</a>&nbsp;';
//		             		}
		             		return taskStatus[data.taskState];
		             		}
		             	},
			            {name : '操作',renderer : function(data) {
			            	var hrefHtml = '<a id="g_detail">清单</a>&nbsp;';
//			            	if('EXCEPTION' === data.taskState){
//		             			
//								hrefHtml += '<a id="g_exception">失败日志</a>&nbsp;';
//							}
			            	hrefHtml += '<a id="g_tracks">轨迹</a>&nbsp;';
			            	return hrefHtml;
						},
						rendererCall : function(obj) {
							var command = {
								"g_detail" : function(data){viewDetail(data);},
								"g_tracks" : function(data){viewTracks(data);}
								};
						
							command[obj.id](obj.data);
						}}]
	});
	
	var viewTracks = function(data){
		dealData = $.extend(data);
		new webBox({
			title 			: '任务轨迹查看',
			url   			: 'pages/monitor/monitor-task-tracks.jsp',
			btn     		: false,
			width			: 650,
			templateRender	: dealData
		}).init().show();
	};
	
	
	var viewException = function(data){
		util.mofangAjax({
			url : "monitor/Task/obtainException.koala",
			data : {taskId : data.id},
			succFun : function(json){
					new webBox({
						title 			: '异常信息查看',
						url   			: 'pages/monitor/monitor-task-exception.jsp',
						btn     		: false,
						templateRender	: {data : json.data}
					}).init().show();
			}
		});
		
	};
	
	var obtainException = function(data, dealData){
		util.mofangAjax({
			url : "monitor/Task/obtainException.koala",
			data : {taskId : data.id},
			succFun : function(json){
				dealData = $.extend({'isProxyIps' : isProxyIps, 'taskStatus' : taskStatus, 'channelObj' : cache.channelMap[data.channelId], 'groupObj' : cache.groupMap[cache.channelMap[data.channelId].group], 'log' : json.data}, data);
				new webBox({
					title 			: '清单',
					url   			: 'pages/monitor/monitor-task-view.jsp',
					btn     		: false,
					templateRender	: dealData
				}).init().show();
			}
		});
	};
	
	
	var viewDetail = function(data){
		var metadata = data.metadata;
		var paramsJson = data.paramsJson;
		try{
			if(typeof metadata === 'string'){
				data.metadata = jQuery.parseJSON(metadata);
			}
			if(typeof paramsJson === 'string'){
				data.paramsJson = jQuery.parseJSON(paramsJson);
			}
		} catch(e){
			//console.log(e.message);
		}
		var channelId = $.trim(data.channelId);
		var dealData = $.extend({'isProxyIps' : isProxyIps, 'taskStatus' : taskStatus, 'channelObj' : cache.channelMap[channelId], 'groupObj' : cache.groupMap[cache.channelMap[channelId].group], 'log' : ''}, data);
		/*if('EXCEPTION' === data.taskState){
			obtainException(data, dealData);
		} else {*/
			new webBox({
				title 			: '清单',
				url   			: 'pages/monitor/monitor-task-view.jsp',
				btn     		: false,
				templateRender	: dealData
			}).init().show();
		//}
	};
	
	var requestData = function() {
		
		util.mofangAjax({
			url       : params.url,
			data      : params.data ,
			succFun   : function(json) {
				_grid.addDatas({
					rowDatas : json.data
				});
				pageTool.render(json.resultCount, params.data.page);
			}

		});
	};
	
	$("#pb_monitorResume").on("click", function(){//恢复按钮事件绑定
		var chechedData = _grid.getCheckDatas();
		if(checkTask(chechedData)){
			var operateData = paramsOperate(chechedData, "DOING");
			requestOperate(operateData);
		}
	});
	
	$("#pb_monitorPause").on("click", function(){//恢复按钮事件绑定
		var chechedData = _grid.getCheckDatas();
		if(checkTask(chechedData)){
			var operateData = paramsOperate(chechedData, "PAUSE");
			requestOperate(operateData);
		}
	});
	
	$("#pb_monitorCancel").on("click", function(){//恢复按钮事件绑定
		var chechedData = _grid.getCheckDatas();
		if(checkTask(chechedData) || cancelByCheckTask(checkData)){
			var operateData = paramsOperate(chechedData, "CANCEL");
			requestOperate(operateData);
		}
	});
	
	var checkTask = function(checkData){//选中任务验证
		var flag = true;
		if(checkData.length == 0){
			$.Prompt("请选择任务后再进行操作");
			flag = false;
		}
		$.each(checkData, function(i, data){
			if(data.taskState == "FINISHED"){
				$.Prompt("请确保您选中的任务中不包含已完成的任务!");
				flag = false;
				return false;
			}
		});
		return flag;
	};
	
	var cancelByCheckTask = function(checkData){//取消任务的验证
		var flag = true;
		$.each(checkData, function(i, data){
			if(data.taskState == "DOING"){
				$.Prompt("请确保您要取消的的任务中不包含已正在执行的任务!");
				flag = false;
				return false;
			}
		});
		return flag;
	};
	
	var paramsOperate = function(rows, status){
		$.each(rows, function(i, row){
				row.taskState = status;
			}
		);
		return rows;
	};
	
	var requestOperate = function(operateData){
		util.mofangAjax({
			url : "monitor/Task/operateTask.koala",
			data : JSON.stringify(operateData),
			dataType : "json",
			contentType : "application/json",
			succFun : function(json){
				if(json.msg == "success"){
					requestData();
				} else {
					$.Prompt("对不起，您的操作失败了!");
				}
				
			}
		});
	};
	

	return {
		init : init
	};
};